package aggregate

import (
	"github.com/casdoor/casdoor-go-sdk/auth"
	"gluenet/modules/manager/server/domain/dependency"
	"gluenet/modules/manager/server/infra"
	"gluenet/modules/manager/server/infra/prepare"
)

func init() {
	//fmt.Printf("init config factory\n")
	prepare.RegisterFactory(func() {
		login := NewLogin()
		prepare.InjectDependency(func() *UserAuth {
			return login
		})
	})
}

func NewLogin() *UserAuth {
	factory := UserAuth{}
	prepare.FetchDependency(&factory.UserRepo)
	return &factory
}

type UserAuth struct {
	Oauth    *infra.OAuth
	UserRepo dependency.UserRepo
}

func (l *UserAuth) Login(code, state string) (string, error) {
	claims, err := l.Oauth.Login(code, state)
	if err != nil {
		return "", err
	}
	//bts,_ := json.Marshal(claims)
	//fmt.Printf("claims: %s\n",bts)

	//user, err := l.UserRepo.Get(claims.ID)
	//if errors.Is(err, infra.DataNotFind) {
	//	user = &entity.Auth{}
	//	user.ID = claims.Id
	//	user.IsAdmin = claims.IsAdmin
	//	user.Name = claims.Name
	//	user.Create = time.Now()
	//	user.Update = time.Now()
	//	user.LastLogin = time.Now()
	//	user.ToKen = claims.AccessToken
	//
	//	if err = l.UserRepo.Save(user);err != nil {
	//		return "", err
	//	}
	//} else if err != nil {
	//	return "", err
	//} else {
	//	user.LastLogin = time.Now()
	//	user.ToKen = claims.AccessToken
	//	err = l.UserRepo.Update(user)
	//	if err != nil {
	//		return "", err
	//	}
	//}
	return claims.AccessToken, nil
}

func (l *UserAuth) Auth(token string) (*auth.Claims, error) {

	claims, err := l.Oauth.Auth(token)
	if err != nil {
		return nil, err
	}
	//
	//obj, err := l.UserRepo.Get(claims.ID)
	//if err != nil {
	//	return nil, err
	//}
	//
	//obj.LastLogin = time.Now()
	//if err = l.UserRepo.Update(obj);err !=nil {
	//	return nil, err
	//}
	//
	//if time.Now().Sub(obj.LastLogin).Seconds() > 300 {
	//	return nil, fmt.Errorf("login expired, please login again")
	//}

	return claims, nil
}
